<template>
  <BasicLayout>
    <template #wrapper>
      <div class="content-box" id="content_box">
        <el-card class="box-card left-box">
          <el-tabs v-model="activeName" stretch @tab-click="handleClick">
            <el-tab-pane label="聊天" name="chat">
<!--              <el-scrollbar class="chat-part-box" :heigth="std_height_render" id="chat_part_box">-->
<!--                <div class="chat-card" v-for="(item,i) in chat_list" >-->
<!--                  <span class="from_name">{{item.from}}：</span>{{item.text}}-->
<!--                </div>-->
<!--              </el-scrollbar>-->
              <div class="chat-part-box" :heigth="std_height_render" id="chat_part_box">
                <div class="chat-card" v-for="(item,i) in chat_list" >
                  <span class="from_name">{{item.type=='web'?decode(item.from):item.from}}：</span>{{item.text}}
                </div>
              </div>
              <div class="chat-action-box">
<!--                <a-textarea class="message-box" @pressEnter="sendMessage"  style="border-radius: 0px;" v-model:value="send_text" placeholder="发送消息" :rows="4" />-->
                <el-input
                  class="message-box"
                  type="textarea"
                  placeholder="发送消息"
                  @change="sendMessage"
                  stlye="height:80px"
                  v-model="send_text">
                </el-input>
                <div class="send-btn" @click="sendMessage">发送</div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="成员" name="member">
              <div class="member-box chat-part-box"  :heigth="std_height_render" :style="'height:'+std_height_render+'px;'">
								<div class="member-card" v-for="(item,i) in channel_members">
                  {{get_member_name(item)}}
								</div>
							</div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
        <el-card class="box-card right-box" style="margin-top: 0px;">
          <div id="id_local_video" style="" />
          <div class="operation-box">
            <el-row style="padding: 10px;color: gray;font-size: .3rem;">
              *通过浏览器捕获对应窗口/界面进行分享采集。
            </el-row>
            <div class="show-info-box">
              <el-form ref="form" :model="zb_info" label-width="80px">
                <el-form-item label="推流链接">
                  <el-input v-model="zb_info.rtmp_url" placeholder="推流链接" />
                </el-form-item>
                <el-form-item label="推流密钥">
                  <el-input v-model="secret" placeholder="推流链接" />
                </el-form-item>
              </el-form>
            </div>
            <!--            <el-input id="pushUrl" v-model="webrtc" placeholder="请替换成实际可用地址，建议 webrtc 开头的地址" />-->
            <!--            <el-button type="text" @click="startCamera(0)">打开摄像头</el-button>-->
            <!--            <el-button type="text" @click="startCamera(1)">关闭摄像头</el-button>-->
            <el-button v-if="!start_flag && !share_flag" plain type="primary" @click="startCamera(2)">共享屏幕</el-button>
            <el-button v-if="!start_flag && share_flag" plain type="danger" @click="startCamera(22)">取消共享屏幕</el-button>
            <el-button v-if="!start_flag && share_flag" type="primary" @click="startCamera(4)">开始直播</el-button>
            <el-button v-if="start_flag" type="danger" plain @click="startCamera(5)">停止直播</el-button>
            <el-button v-if="!hasVoice" type="text" icon="el-icon-turn-off-microphone" @click="startCamera(3)">开启声音</el-button>
            <el-button v-if="hasVoice" type="text" icon=" el-icon-microphone" @click="startCamera(33)">关闭声音</el-button>
          </div>

        </el-card>
      </div>
    </template>
  </BasicLayout>
</template>

<script>
import { startLive, changeLiveState } from '@/api/admin/sys-course'
import { getUserProfile } from '@/api/admin/sys-user'
import ArRTM from 'ar-rtm-sdk'
export default {
  name: 'LiveWindowVue2',
  data() {
    return {
      livePusher: null,
      webrtc: '',
      start_flag: false, // 是否正在直播
      share_flag: false, // 是否正在分享屏幕
      hasVoice: false, // 是否有声音
      courseInfo: {},
      activeName: 'chat',
      px_list: ['720px', '1080p'], // 分辨率数组，开播时可选
      zb_info: {}, // 直播链接信息
      secret: '',
      // 直播互动
      APPID: 'f883b55d74a5acd97b4ee840f8518846',
      client: '',
      userInfo: null,
      login_name:'',
      channel:'',
      chat_list:[],
      channel_members:[],
      std_height_render:0,
      send_text:''
    }
  },
  computed: {
    player() {
      return this.$refs.videoPlayer.player
    },
    currentStream() {
      return this.currentTech === 'Flash' ? 'RTMP' : 'HLS'
    }
  },
  created() {
    if (this.$route.params.end_time) {
      this.$route.params.end_time = this.$route.params.end_time.replace('Z', '')
      this.$route.params.end_time = this.$route.params.end_time.replace('T', ' ')
      var plus_index = this.$route.params.end_time.indexOf('+')
      this.$route.params.end_time = this.$route.params.end_time.slice(0, plus_index)
    }
    this.courseInfo = this.$route.params
    this.startLive()
    this.getScript()
    // this.newTxList()
  },
  mounted() {
    const _this = this
    window.onbeforeunload = function(e) {
      console.log(e)
      // eslint-disable-next-line no-mixed-spaces-and-tabs
		  var msg = '您网页上有东西未保存'
      // eslint-disable-next-line no-mixed-spaces-and-tabs
		  e = e || window.event
      // eslint-disable-next-line no-mixed-spaces-and-tabs
		  e.returnValue = msg
      // eslint-disable-next-line no-mixed-spaces-and-tabs
		  return msg
    }
    window.onnload = function(e) {
      _this.changeState(-1)
    }
    // 获取用户信息
    this.getUser()
    // 直播互动
    this.client = ArRTM.createInstance(this.APPID) // 创建实例
  },
  methods: {
    get_member_name(str) {
      let fit_str = ''
      // console.log(str)
        if(str.includes('web')) {
          fit_str = this.decode(str.split('.')[0])
        }
        else{
          fit_str = str.split('.')[0]
        }
        return fit_str
    },
    encode(str) {
      return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
        function toSolidBytes(match, p1) {
          return String.fromCharCode('0x' + p1)
        }))
    },
    decode(str) {
      return decodeURIComponent(atob(str).split('').map(function(c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
      }).join(''))
    },
    async getUser() {
      const res = await getUserProfile()
      if (res.code == 200) {
        this.userInfo = res.data.user
        console.log(this.userInfo)
        if (this.userInfo) {
          this.login_name = this.userInfo.nickName? this.encode(this.userInfo.nickName)+".web":`mr.${this.userInfo.userId}.web`
          this.clientLogin()
        }
      }
    },
    async clientLogin() {
      // 定义登录配置
      const options = {
        token: '',
        uid: this.login_name // 不能用中文
      }
      // 登录
      const res = await this.client.login(options)
      this.createChannel_fun()
    },
    createChannel_fun(){ // 创建频道
      console.log(this.courseInfo)
      // return
      let course_info = this.courseInfo
      // course_info = JSON.parse(decodeURIComponent(route.params.str))
      if(course_info) {
        // course_title.value = course_info.name
        // video_src.value = course_info.m3u8_url
        // 查看直播
        // living_vide_paly()
        // 确认高度
        var std_height = content_box.offsetHeight
        chat_part_box.style.height = (std_height-150)+'px'
        this.std_height_render = std_height-150

        // 创建频道
        var channelID = this.generateChannelID(course_info.id)
        this.channel = this.client.createChannel(channelID)
        // 加入频道
        this.channel.join().then(() => {
          console.log('加入频道成功')
          // 加入频道成功
        }).catch(error => {
          // 加入频道失败
          console.log('加入频道失败:',error)
        });
        // 监听频道
        if(this.channel) {
          this.channel.on('ChannelMessage', ({ text }, senderId) => {
            // text 为收到的频道消息文本，senderId 为发送方的 User ID
            // console.log("消息来自：",senderId)
            // console.log("消息内容：",text)
            let from_type = senderId.split(".")[1]
					  let rel_name = senderId.split(".")[0]
            var new_data = {
              from:rel_name,
              text:text,
              type:from_type
            }
            this.chat_list.push(new_data)
            this.scrollListener()
          });
        }
        // 频道成员
        this.channel.getMembers().then(members => {
          console.log(members)
          this.channel_members = members
        }).catch(err => {
          console.log(err)
        })
      }
    },
    generateChannelID(current_id){
      current_id = current_id.toString()
      var fit_id = ''
      if(current_id.length >= 32) {
        fit_id = current_id.slice(0,32)
      }
      else{
        const APPID_length = this.APPID.length
        const half_str = this.APPID.slice(0,APPID_length - current_id.length)
        fit_id = half_str + current_id
      }
      return fit_id
    },
    scrollListener(){
      this.$nextTick(() => {
        // let scroll_el = document.querySelector('#chat_part_box .el-scrollbar__wrap')
        let scroll_el = document.querySelector('#chat_part_box')
        if(scroll_el.scrollHeight > scroll_el.clientHeight) {
          //设置滚动条到最底部
          scroll_el.scrollTop = scroll_el.scrollHeight;
        }
      })

    },
    sendMessage(){ // 发送消息 监听回车
      let new_val =this.send_text? this.send_text.trim():''
      if(new_val) {
        this.channel.sendMessage(
          { text: this.send_text }, // 发送文本消息
          {
            enableHistoricalMessaging: false // 是否保存为历史消息
          }
        ).then(() => {
          // 频道消息发送成功
          console.log('频道消息发送成功')
          let from_type = this.login_name.split(".")[1]
          let rel_name = this.login_name.split(".")[0]
          var new_data = {
            from:rel_name,
            text:this.send_text,
            type:from_type
          }
          this.chat_list.push(new_data)
          this.send_text = ''
          this.scrollListener()
        }).catch(error => {
          // 频道消息发送失败
          console.log('频道消息发送失败:',error)
        });
      }
      else{
        this.send_text = null
      }
    },
    getSecret(secret) {
      // var reg = /=\w+/
      // var str = secret.match(reg)[0]
      // this.secret = str.replace('=', '')
      // console.log(this.secret,secret)
      this.secret = secret
    },
    handleClick(tab, event) {
    },
    async startLive() {
      const res = await startLive({
        id: this.courseInfo.id?.toString(),
        end_time: this.courseInfo.end_time?.toString()
      })
      this.zb_info = res.data
      this.webrtc = res.data.webrtc
      this.getSecret(this.zb_info.secret)
    },
    getScript() {
      const script = document.createElement('script')
      script.type = 'text/javascript'
      script.src = 'https://video.sdk.qcloudecdn.com/web/TXLivePusher-2.0.1.min.js'
      document.getElementsByTagName('head')[0].appendChild(script)
    },
    newTxList() {
      this.livePusher = new TXLivePusher()
    },
    // 打开摄像头
    startCamera(type) {
      if (!this.livePusher) { // 创建实例
        this.newTxList()
      }
      // 指定本地视频播放器容器：
      this.livePusher.setRenderView('id_local_video')
      // 设置视频质量
      this.livePusher.setVideoQuality('1080p')
      // 设置音频质量
      this.livePusher.setAudioQuality('standard')
      // 自定义设置帧率
      this.livePusher.setProperty('setVideoFPS', 25)
      // 消除回声
      this.livePusher.setProperty('enableAudioAEC', true)
      // 启用自动增益
      this.livePusher.setProperty('enableAudioAGC', true)
      // 启用噪声抑制
      this.livePusher.setProperty('enableAudioANS', true)

      if (type == 0) { // 打开摄像头
        // 采集完摄像头画面后自动推流
        this.livePusher.startCamera().then(function() {
          // this.livePusher.startPush('webrtc://domain/AppName/StreamName?txSecret=xxx&txTime=xxx');
        }).catch(function(error) {
          console.log('打开摄像头失败: ' + error.toString())
          this.msgError('打开摄像头失败: 请检查设备')
        })
      } else if (type == 1) { // 关闭摄像头
        this.livePusher.stopCamera()
      } else if (type == 2) { // 共享屏幕
        this.livePusher.stopCamera()
        this.livePusher.startScreenCapture({
          audio: true
        }).then(() => {
          this.share_flag = true
        })
      } else if (type == 22) { // 停止屏幕分享
        this.livePusher.stopScreenCapture()
        this.share_flag = false
      } else if (type == 3) { // 开启声音
        this.livePusher.startMicrophone().then(streamId => {
          console.log('microphone stream id is ' + streamId)
          this.hasVoice = true
        }).catch(error => {
          console.log(error)
          this.msgError('开启声音失败: 请检查设备 ')
        })
      } else if (type == 33) { // 关闭声音
        this.livePusher.startMicrophone()
        this.hasVoice = false
      } else if (type == 4) { // 开始直播
        console.log(this.webrtc)
        this.livePusher.startPush(this.webrtc).then(() => {
          this.start_flag = true
          this.changeState(2)
        }).catch(err => {
          console.log(err)
          this.msgError('开播失败: 请检查网络或联系管理员 ')
        })
      } else if (type == 5) { // 停止直播
        this.livePusher.stopPush()
        this.start_flag = false
        this.changeState(-1)
      }
    },
    changeState(state) {
      // console.log(this.courseInfo); return
      // 改变直播状态
      var params = {
        id: this.courseInfo.id,
        is_live: state
      }
      changeLiveState(params).then(res => {
        console.log(res)
        this.channel.leave()
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>
<style scoped>
.course_title{
		width: 80%;
	    margin: 0 auto;
	    font-size: 20px;
	    /* font-family: 'yuanti'; */
	    font-weight: 800;
	    padding: 5px 0;
	}
	.member-card{
		color: #1890ff;
	    padding: 5px 0;
	}
	.chat-card{
		/*white-space: ;*/
	}
	.chat-card{
		padding:10px 0;
	}
	.from_name{
		color: #1890ff;
	}
	.send-btn{
		position: absolute;
	    bottom: 0;
	    right: 0px;
	    height: 80px;
	    line-height: 80px;
	    padding: 0 20px;
	    background: #005e54;
	    color: white;
	    cursor: pointer;
	}
	.message-box{
		max-height: 80px;
		height: 80px;
	    padding-right: 68px;
	}
	.chatroom-box{
		background: white;
		position: relative;
		width: 250px !important;
	}
	.chat-action-box{
		position: absolute;
		bottom: 0px;
		width: 100%;
	}
	.chat-part-box{
		max-height:100%;
	    padding: 0 10px;
	    overflow: auto;
	        margin-bottom: 80px;
	}
	.content-box{
		display: flex;
	}
	.content-box .content-layout{
		width: 50%;
	}
	.ant-tabs-content{
		display: unset;
		height: 100%;
	}
</style>
<style>
.message-box>textarea{
  height: 100%;
}
.content-box{
  display: flex;
  width: 1350px;
  margin: 0 auto;
}
.left-box{
  width: 320px;
  min-width: 320px;
}
.right-box{
  /*width: 75%;*/
  margin-left: 10px;
  width: 900px;
  min-width: 900px;
  /*max-height:600px;*/
}
.el-card__body{
  height: 100%;
}
#id_local_video{
  width:100%;
  /*height:100%;*/
  background:#f3f3f3;
  /*min-height:320px;*/
  min-height: 485px;
}
.left-list{
  max-height: 700px;
}
</style>
